import threading
from pytdx.hq import TdxHq_API

ips = ['110.41.147.114', '8.129.13.54', '120.24.149.49', '8.129.174.169', '110.41.154.219']
apis = []
l = 0
p = 0
locker = threading.Lock()
for i in range(40):
    ip = ips[i % len(ips)]
    api = TdxHq_API(raise_exception=False)
    api.connect(ip, 7709)
    apis.append(api)
    l += 1


def get_api():
    global l, p, apis
    locker.acquire()
    if l == 0:
        ip = ips[p]
        api = TdxHq_API(raise_exception=False)
        api.connect(ip, 7709)
        p = (p + 1) % len(ips)
        locker.release()
        return api
    else:
        api = apis[0]
        apis = apis[1:]
        l -= 1
        locker.release()
        return api


def release(api):
    global l, apis
    apis.append(api)
    l += 1


def close():
    for api in apis:
        api.close()


if __name__ == '__main__':
    print('----------')
    arr = []
    for i in range(6):
        api = get_api()
        arr.append(api)
    print(apis)
    print(l)
    print(p)
    release(arr[0])
    release(arr[1])
    release(arr[2])
    print(apis)
    print(l)
    print(p)
    release(arr[3])
    release(arr[4])
    release(arr[5])
    print(apis)
    print(l)
    print(p)
